package tests;

public class Keyongyu {
    static class Node {
        String data;
        Node next;

        public Node(String data) {
            this.data = data;
        }

        @Override
        public String toString() {
            return "Node{" + data + "}->" + next;
        }
    }

    public static Node reverse(Node root) {
        if (root == null || root.next == null)
            return root;
        Node temp = root.next;//初始化的next节点存在临时变量
        Node newRoot = reverse(root.next);//相当于root抽出来，从next开始进行反转
        temp.next = root;//不用管root的next怎么变化，只需要root跟在初始化的next节点后面就行了
        root.next = null;
        return newRoot;
    }

    public static void main(String[] args) {
        Node root = new Node("1");
        Node last = root;
        for (int i = 2; i < 19; i++) {
            Node node = new Node("" + i);
            last.next = node;
            last = node;
        }
        System.out.println("before:" + root);
        Node newNode = reverse(root);
        System.out.println("after:" + newNode);
    }
}